# -*- coding:utf-8 -*-
"""
作者：Wangzhicheng
日期：2024年07月16日11:26
@file download.py

download  ------>模块
"""
import time

import requests
import json

# 封装一个函数，实现获取网页数据
# get方式获取，返回text
# 自适应页面编码

def get_content(url):
    headers={
        "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
    }
    # try 检测异常,如果遇到异常会跳转到expect分支
    try:
        print(f"正在访问{url}......")
        response=requests.get(url,headers=headers)
        response.raise_for_status()
        response.encoding=response.apparent_encoding
        return response.content
    except:
        print(f"访问{url}出错！")
        return b""


def get_text(url):
    headers={
        "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
    }
    # try 检测异常,如果遇到异常会跳转到expect分支
    try:
        print(f"正在访问{url}......")
        time.sleep(3)
        response=requests.get(url,headers=headers)
        response.raise_for_status()
        response.encoding=response.apparent_encoding
        return response.text
    except:
        print(f"访问{url}出错！")
        return b""


def get_json(url):
    headers={
        "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0"
    }
    # try 检测异常,如果遇到异常会跳转到expect分支
    try:
        print(f"正在访问{url}......")
        response=requests.get(url,headers=headers)
        response.raise_for_status()
        response.encoding=response.apparent_encoding
        return json.loads(response.text)
    except:
        print(f"访问{url}出错！")
        return b""


# 测试代码要像下面这样写:
#                 如果直接执行当前文件，__name__的值为 __name__
#                 当是被当成模块导入的时候，__name__的值为download(文件名)
if(__name__)=="__name__":
    print(get_text("https://www.baidu.com"))